package P150;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LiangMu
 * @version \$Id: P33.java, v 0.1, 2024年07月05日 23:35 LiangMu Exp $$
 */
public class P33 {

    public static List<Integer> spiralOrder(int[][] matrix) {
        // 右，下，左，上
        int[][] direct = new int[][]{
            {0, 1}, {1, 0}, {0, -1}, {-1, 0}
        };
        int directIndex = 0, count = matrix.length * matrix[0].length;
        int i = 0, j = 0, k = 0;
        List<Integer> result = new ArrayList<>(count);
        while (k < count) {
            result.add(matrix[i][j]);
            matrix[i][j] = -101;
            ++k;
            int rIndex = direct[directIndex][0] + i;
            int cIndex = direct[directIndex][1] + j;
            if (rIndex >= 0 && rIndex < matrix.length && cIndex >= 0 && cIndex < matrix[0].length) {
                if (matrix[rIndex][cIndex] == -101) {
                    directIndex = (directIndex + 1) % 4;
                    i = direct[directIndex][0] + i;
                    j = direct[directIndex][1] + j;
                } else {
                    i = rIndex;
                    j = cIndex;
                }
            } else {
                directIndex = (directIndex + 1) % 4;
                i = direct[directIndex][0] + i;
                j = direct[directIndex][1] + j;
            }
        }
        return result;
    }


    public static void main(String[] args) {
        /**
         * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
         * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
         */

        int[][] matrix = {
            {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}
        };
        System.out.println(spiralOrder(matrix));
    }

}
